<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Epi/Epi.php';
Epi::setSetting('exceptions', true);
Epi::init('api');

class API{
	protected $inited=false;
	protected $routes=false;
	protected static $_instance;
	public static $lang='ru';
	public static $dbConf='';
	

	private function __construct(){}
	private function __clone(){}
	public static function inst($routes){
	  if( null===self::$_instance ){
	    self::$_instance=new self();
		}
		self::$_instance->routes=$routes;
		return self::$_instance;
	}
	
	public function setLang($ln){
		if(  preg_match('~[A-Za-z]{2}~', $ln) ){
	    self::$lang=mb_strtolower($ln, 'utf8');
		}
	}

	public static function setDBConf($fileName){
		self::$dbConf=$fileName;
	}

	
	public function init(){
		$this->API=getApi();
	
	  if(!$this->load_rules()) return false;

		$this->inited=true;
	  
	  if(!empty($_GET['lang']) )	self::setLang($_GET['lang']);

	  return true;
	}

	public function load_rules(){
		//читаю и регистрирую пути для роутера и API
		if(!self::$_instance->routes)	throw_error('Api routing config not found');

		foreach( self::$_instance->routes as $k=>$v ){
			/*v0-method v1-path v2-file/class/method */
			$ctrl=explode('/', $v[2]);
			$cnt=count($ctrl);

			if( $cnt<2 ) throw_error("Router config error in controller path expected class/method '". $v[3] ."' given");
			
		  //if( !file_exists($_SERVER['DOCUMENT_ROOT'].'/lib/'.$ctrl[0].'.php') ) throw_error("Controller file '".$ctrl[0].".php' not found");
		  //include_once($_SERVER['DOCUMENT_ROOT'].'/lib/'.$ctrl[0].'.php');
		  //if( !class_exists($ctrl[0]) )	throw_error('Controller class not found in '.$ctrl[0].'.php');
			//Так делать нельзя, потому что в классе Geo методы магические
			
      $prm=array();
      if( !empty($v[3]) ){
        parse_str($v[3], $t);
        foreach($t as $key=>$rega){
          if( isset($_REQUEST[$key]) && preg_match('~'.$rega.'~', $_REQUEST[$key]) ){
            $prm[$key]=$_REQUEST[$key];
					}
				}
			}
			
			switch( mb_strtolower($v[0], 'utf8') ){
			  case 'get':
					$this->API->get($v[1], array($ctrl[0],$ctrl[1]),EpiApi::external,$prm);
					break;
			  case 'post':
					$this->API->post($v[1], array($ctrl[0],$ctrl[1]),EpiApi::external,$prm);
					break;
			  case 'put':
					$this->API->put($v[1], array($ctrl[0],$ctrl[1]),EpiApi::external,$prm);
					break;
			  case 'delete':
					$this->API->delete($v[1], array($ctrl[0],$ctrl[1]),EpiApi::external,$prm);
					break;
				default:{
				  throw_error('Method '.$v[0].' not supported');
				}
			}
			$this->method=$v[0];
		}
		return true;
	}
	
	public function run(){
	  if(!$this->inited && !$this->init()) throw_error('init router error');
	  try{
			getRoute()->run();
		}catch(Exception $e){
		  throw_error($e->getMessage(),500);
		}
	}

	public function invoke($route, $httpMethod = EpiRoute::httpGet, $params = array()){
	  return $this->API->invoke($route,$httpMethod,$params);
	}
}
?>